/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TweetRay;

import java.util.ArrayList;

/**
 *
 *           __
 *          /  \
 *          ^  ^
 *         / \/ \
 *         | .| .|
 *         \_/\_/
 *          |  |
 *          \ o/
 *          /  \
 *         |    |
 *         | | ||
 *         | 0 0|
 *         |    |
 */
public class UTFWriter {

    private ArrayList<Integer> bytes;
    private int buffer;
    int bitCount = 0;

    public UTFWriter() {
        bytes = new ArrayList();
    }
    public ArrayList <Integer> getBytes(){
        flush();
        
        
        ArrayList <Integer> tmp = new ArrayList<Integer>();
        for (Integer i:bytes){
            tmp.add(new Integer(i.intValue()));
        }
        
        return tmp;
    }
    
    
    public void writeByte(int in){
        if (buffer != 0 ) align14();
        bytes.add(in);
    }
    public void writeUTF(int in){
        if (buffer != 0 ) align14();
        bytes.add(in);
    }

    public void writeBits(int value, int numBits) {

        
        //new
        while (numBits > 0) {
            numBits--;
            int mix = ((value & 1) << bitCount++);
            buffer |= mix;
            value >>= 1;
            if (bitCount == 14) {
                align14();
            }
        }



    }

    private void align14() {
        if (bitCount > 0) {
            bitCount = 0;
            bytes.add(buffer + 0x51cf); //add utf 51cf offset to get this into the unified CJK charset
            buffer = 0;
        }
    }

    public void flush() {
        align14();
    }

    public Integer getPackedInteger() {
        Integer toRet = bytes.get(0);
        bytes.remove(toRet);
        return toRet;
    }

    
    
    public String getUTF8() {
        flush();

        String out = "";
        
        while(!bytes.isEmpty())    {
        out += "&#x";// I know I should use stringbuffer, but I'm feeling saucy
        out += Integer.toHexString(getPackedInteger());

        out += ";";
        }
        return out;

    }
}
